# -*- encoding: utf-8 -*-
'''
Created on Jul 10, 2010

@author: dgentry
'''

import sqlite3
from datetime import datetime
import urllib

def as_item(title,url,pull_date):
    item = '\n<item>\n<title>'
    item += title
    item += '</title>\n<link>'
    item += url
    item += '</link>\n<pubDate>'
    item += pull_date.strftime('%a, %d %b %Y %H:%M:%S ') + '-0400'
    item += '</pubDate>\n'
    item += '''<dc:creator>drew</dc:creator>
<category><![CDATA[audio]]></category>
<guid isPermaLink="false">'''
    item += url
    item += '</guid>\n'
    item += '<description><![CDATA['
    item += title
    item += ' - A random selection from the DND archives]]></description>\n'
    item += '<content:encoded><![CDATA[<p>'
    item += title
    item += ''' - A random selection from the DND archives</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" 
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" align="middle" height="27" width="400">
<param name="quality" value="best"></param><param name="allowScriptAccess" value="never"></param><param name="wmode" value="window"></param>
<param name="movie" value="'''
    item += urllib.quote_plus(url)  ## escaped
    item += '''">
<embed classname="audio-player-embed" type="application/x-shockwave-flash" src="http://dawnanddrew.com/googleplayer.swf?audioUrl='''
    item += urllib.quote_plus(url)  ## escaped
    item += '" allowscriptaccess="never" quality="best" bgcolor="#ffffff" wmode="window" flashvars="playerMode=embedded" pluginspage="http://www.macromedia.com/go/getflashplayer" height="27" width="400"></embed></param></object></p>'
    item += '''
<ul>
<li><a href="'''
    item += url
    item += '" title="'
    item += title
    item += '''" target="_blank"><strong>DOWNLOAD THE MP3</strong></a></li>
<li><strong>call us @ 206-666-3825</strong></li>
<li><a href="https://phobos.apple.com/WebObjects/MZFinance.woa/wa/addUserReview?type=Podcast&#038;id=73331700" title="leave feedback in iTunes">leave feedback in iTunes</a></li>
</ul>
<p><strong><a href="http://dawnanddrew.com/support">please help support the show, thanks</a></strong></p>
]]></content:encoded>
'''    
    item += '<enclosure url="'
    item += url
    item += '" length="0" type="audio/mpeg" />\n</item>\n'
    
    return item


if __name__ == '__main__':
    #  open database
    
    conn = sqlite3.connect('db')
    
    c1 = conn.cursor() # for inquiry
    c2 = conn.cursor() # for insert
    
    
    #  get random record
    
    print "Selecting random episode"
    
    c1.execute('SELECT * FROM podcasts ORDER BY RANDOM() LIMIT 1;')
    
    #  insert in choices table
    
    for r in c1:
        print "Selected", r[0]
        # t is: title, url, pull_date
        t = (r[0], r[1],datetime.today().strftime('%Y%m%d%H%M%S') )
        c2.execute('insert into choices values (?,?,?)', t)
        conn.commit()        
        break
    
    #  open file for write
    
    f = open('random_feed.rss', 'w')
    
    print "Writing RSS file"
    
    #  write header
    
    header1 = '''<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    >

<channel>
    <title>The Dawn and Drew Show! &#187; random</title>
    <atom:link href="http://gentryville.net/random_feed7.rss" rel="self" type="application/rss+xml" />
    <link>http://thedawnanddrewshow.com</link>
    <description>podcasting since september 2004, dawn miceli and drew domkus, two ex gutter punks who fall in love, buy a retired farm in southeast wisconsin and tell the world their dirty secrets… always profane, rarely profound.</description>
    <lastBuildDate>'''
    
    header2 = '''</lastBuildDate>
    <generator>Random Feed by Dashdrum - http://dashdrum.com</generator>
    <language>en</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <cloud domain='thedawnanddrewshow.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
'''
    
    header = header1 + datetime.today().strftime('%a, %d %b %Y %H:%M:%S %z') + '-0400' + header2
    
    f.write(header)
    
    #  grab last 15 previous choices (including new choice) and write items
    
    c1.execute('SELECT * FROM choices ORDER BY pull_date DESC LIMIT 15;')
    
    for r in c1:
        f.write(as_item(r[0],r[1],datetime.strptime(r[2],'%Y%m%d%H%M%S')))
    
    
    #  write footer
    
    footer = '''
    </channel>
</rss>'''
    f.write(footer)
    
    print "File write complete"
    
    #  close file
    
    f.close()
    conn.close()